﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.UI.Controls;
using Medianamik.UI.Mediasend.Logic;
using Medianamik.Core;
using Medianamik.Core.Sugar;
using Medianamik.Globalization;
using NLog;
using System.Globalization;

namespace Medianamik.UI.Mediasend.UserControls
{
    /// <summary>
    /// Affichage de l'ensemble des campainges Mediasend du client
    /// </summary>
    public partial class ucCampaignSelection : MediasendUserControl
    {
        /// <summary>
        /// Configuration du treeview
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            trvCampaigns.NeedChildren += trvCampaigns_NeedChildren;
            trvCampaigns.NeedSelfAndParents += trvCampaigns_NeedSelfAndParents;

            trvCampaigns.Skin = Skins.DEFAULT_SKIN;
            trvCampaigns.EnableEmbeddedSkins = Skins.DEFAULT_USE_EMBEDDED_SKIN;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetControls();
            }

        }

        
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            string specializedScriptName = "OnClientNodeClickingHandlerFor" + trvCampaigns.ClientID;

            trvCampaigns.OnClientNodeClicking = specializedScriptName;

            //Le script doit exister (différent) pour chaque instance de ComboTree
            string specializedScript = String.Concat("function " + specializedScriptName + "(sender, args) {\n",
                    " var node = args.get_node();\n",
                    "if (node.get_category() == \"Disabled\") {\n",
                        "args.set_cancel(true);}\n",
                        "}\n");
            ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), specializedScriptName, specializedScript, true);
        }

        /// <summary>
        /// Validation de la sélection d'un élément du treeview.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>
        protected void cvSelectCampaign_Validate(object source, ServerValidateEventArgs args)
        {
            int dummyTest;
            args.IsValid = int.TryParse(trvCampaigns.SelectedValue, out dummyTest);
        }

        #region " TREEVIEW " 
            void trvCampaigns_NeedChildren(object sender, Medianamik.UI.Controls.NeedChildrenEventArgs e)
            {
                if ((e.ParentValue ?? "").Trim() == "")
                {
                    var mediasend = MediasendManager.Instance.OpenSession(Configuration.Instance.Properties.Username,
                                                                          Configuration.Instance.Properties.Password);

                    try
                    {
                        var nodes = from campaign in mediasend.GetCampaigns()
                                    where campaign.Status == CampaignStatus.Ongoing
                                    select
                                        (ITreeItem)
                                        (new TreeItem(campaign.Name, campaign.ID.ToString(), null, null, false, !Data.AlreadyBeenSaved));

                        e.ChildNodes.AddRange(nodes);
                    }
                    catch (Exception exc)
                    {
                        var logger = LogManager.GetLogger("ActivityLogger");
                        if (MediasendManager.Instance.LastError != "")
                            logger.ErrorException("Error while getting campaings : " + MediasendManager.Instance.LastError, exc);
                        else
                            logger.ErrorException("Error while getting campaings", exc);

                        GlobalError = Translator.Translate("Medianamik_Mediasend", "ErrorPleaseContactSupport");
                    }
                }
            }

            void trvCampaigns_NeedSelfAndParents(object sender, NeedSelfAndParentsEventArgs e)
            {
                e.Items.Add(new TreeItem(Translator.Translate("Medianamik_Mediasend","Campaign"), null, null, null, true, true, int.MinValue, false));
            }

        #endregion

        #region IMediasendUserControl Members

            public override bool Save()
            {
                int cpgId;
                if (int.TryParse(trvCampaigns.SelectedValue, out cpgId))
                {
                    if (!Data.AlreadyBeenSaved) //Si le mailing a déjà été sauvegardé, il est impossible de le changer de campagne.
                        Data.CampaingId = cpgId;

                    return true;
                }
                else
                {
                    return false;                    
                }
            }

            public override void SetControls()
            {
                trvCampaigns.CurrentItemValue = Data.CampaingId.ToString();

                //Si le mailing a déjà été sauvegardé, il est impossible de le changer de campagne.
                trvCampaigns.Enabled = !Data.AlreadyBeenSaved;
                lblCampaingSavedWarning.Visible = Data.AlreadyBeenSaved;
            }

        #endregion
    }
}